import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import re
import numpy as np
file1=open(sys.argv[1],'r')
fig = plt.figure(figsize=(30,5))
matplotlib.rcParams['pdf.fonttype']=42
gs = matplotlib.gridspec.GridSpec(1,1)
ax1 = fig.add_subplot(gs[0:1,0:1],facecolor='white')

snp_num_list=[]
chr_dict={}
for line in file1:
    line_list=line.strip().split('\t')
    snp_num_list.append(int(line_list[4]))
    if int(line_list[4])<100:
        continue
    if line_list[0] in chr_dict.keys():
        chr_dict[line_list[0]].append([float(line_list[2]),float(line_list[3]),int(line_list[4]),int(line_list[1])])
    else:
        chr_dict[line_list[0]]=[[float(line_list[2]),float(line_list[3]),int(line_list[4]),int(line_list[1])]]
chr_list=sorted(chr_dict.keys(),key=lambda x:int(re.findall('\d+',x)[0]))
total_list_y=[]
total_list_y1=[]
total_list_x=[]
start=0
chr_pos_list=[]
chr_name_list=[]
chr_pos2_list=[]
color_list=[]
big_num=np.percentile(snp_num_list,90)
print(big_num)
for chr in chr_list:
    chr_name_list.append(chr)
    chr_pos2_list.append(start+chr_dict[chr][-1][-1]/2)
    chr_pos_list.append([chr,start+chr_dict[chr][-1][-1]/2,start])
    for i in chr_dict[chr]:
        total_list_x.append(i[3]+start)
        total_list_y.append(i[0])
        total_list_y1.append(i[1])
        if i[2]>big_num:
            color_list.append(big_num)
        else:
            color_list.append(i[2])
    start+=chr_dict[chr][-1][-1]
for chr in chr_pos_list:
    plt.axvline(chr[2],ls="--",c="black",linewidth='0.3')
ax1.plot(total_list_x,total_list_y,color='#ed1c24')
axx=ax1.scatter(total_list_x,total_list_y1,s=2,c=color_list,cmap='plasma_r')

# plt.ylim([0.75,0.78])
plt.xlim([0,start])
plt.xticks(chr_pos2_list,chr_name_list,fontsize=15)
plt.yticks(fontsize=15)
position=fig.add_axes([0.55, 0.01, 0.3, 0.02])
fig.colorbar(axx,ax=ax1,cax=position,orientation='horizontal')
plt.savefig(sys.argv[1]+'.png',bbox_inches="tight",pad_inches=0.6,dpi=600)    
